import os
import uvicorn
from utils.logger import logger
from utils.config import config
from fastapi import FastAPI, Request
from utils.send import wechatSend, dingtalkSend
from utils.template import firing_template, resolved_template

app = FastAPI(docs_url=None, redoc_url=None)


@app.on_event("startup")
async def start_event():
    logger.info("Alarm plugin started successfully, Current PID: %s" % os.getpid())


@app.on_event("shutdown")
async def shutdown_event():
    logger.info("Alarm plugin shutdown completed, Current PID: %s" % os.getpid())


@app.post('/{apis}/{ids}')
async def api(request: Request):
    data = {"client": request.client, "url": request.url}
    logger.error(data)
    return data


@app.get('/{apis}/{ids}')
async def api(request: Request):
    data = {"client": request.client, "url": request.url}
    logger.error(data)
    return data


@app.post('/{apis}')
async def api(request: Request):
    data = {"client": request.client, "url": request.url}
    logger.error(data)
    return data


@app.get('/{apis}')
async def api(request: Request):
    data = {"client": request.client, "url": request.url}
    logger.error(data)
    return data

# 企业微信告警插件
@app.post("/webhook/wechat/send")
async def wechat(data: dict, request: Request):
    logger.info({"client": request.client, "url": request.url})
    if data['status'] == "firing":
        content = firing_template(data['alerts'])
        response = wechatSend(content.strip('---'))
    elif data['status'] == "resolved":
        content = resolved_template(data['alerts'])
        response = wechatSend(content.strip('---'))
    else:
        response = wechatSend(str(data))
    return response


# 钉钉告警插件

@app.post("/webhook/dingtalk/send")
async def dingtalk(data: dict, request: Request):
    logger.info({"client": request.client, "url": request.url})
    if data['status'] == "firing":
        content = firing_template(data['alerts'])
        response = dingtalkSend(content)
    elif data['status'] == "resolved":
        content = resolved_template(data['alerts'])
        response = dingtalkSend(content)
    else:
        response = dingtalkSend(str(data))
    return response


if __name__ == '__main__':
    uvicorn.run("main:app", host=config.host(), port=config.port())

